package com.ibm.psbc.cloud;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
 
/**
 * 异步执行HTTP请求
 */
public class HttpCallable implements Callable<String> {
    
    private String url;
    
    private String jsonParams;
    
    public HttpCallable(String url, String jsonParams){
        this.url = url;
        this.jsonParams = jsonParams;
    }
 
    /**
     * 执行并返回结果
     */
    @Override
    public String call() throws Exception {
        return HttpTool.requestPost(url, jsonParams);
    }
    
    /**
     * 模拟并发测试
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //模拟并发数
        int concurrencyNumber = 100;
        
        List<String>  resList = Lists.newArrayList();
        
        //执行线程池
        ExecutorService ex = Executors.newFixedThreadPool(100);
        
        String url = "http://localhost:8090/echo/johnny33?pn=1";
        Map<String, String> mapPatam = new HashMap<>();
        mapPatam.put("name", "测试");
        
        int success = 0;
        int failed = 0;
        for(int i =0 ; i< concurrencyNumber; i++){
            Future<String> callRes = ex.submit(new HttpCallable(url, JSON.toJSONString(mapPatam)));
            String rst = callRes.get();
            if ("Hello Nacos Discovery johnny33".equals(rst)) {
            	success++;
            }
			resList.add(i + ">>>" + rst);
        }
        
        for(String s : resList){
            System.out.println("------>" + s);
        }
        System.out.println("sucessed:" + success);
    }
 
}
